package com.pai4j.zwiki.controller;

import com.pai4j.zwiki.domain.entity.ZWikiTaskQueueEntity;
import com.pai4j.zwiki.service.ZWikiTaskQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务队列控制器
 * 提供任务队列状态查询接口
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/queue")
@RequiredArgsConstructor
public class TaskQueueController {

    private final ZWikiTaskQueueService taskQueueService;

    private static final String CODE_SUCCESS = "0";
    private static final String CODE_NOT_FOUND = "404";
    private static final String CODE_ERROR = "500";

    /**
     * 查询任务队列状态
     */
    @GetMapping("/status/{taskId}")
    public ResponseEntity<Map<String, Object>> getTaskQueueStatus(@PathVariable String taskId) {
        log.info("查询任务队列状态: {}", taskId);

        try {
            ZWikiTaskQueueEntity taskQueue = taskQueueService.getTaskQueueStatus(taskId);

            Map<String, Object> data = new HashMap<>();
            data.put("taskId", taskQueue.getTaskId());
            data.put("userId", taskQueue.getUserId());
            data.put("taskType", taskQueue.getTaskType());
            data.put("status", taskQueue.getStatus());
            data.put("priority", taskQueue.getPriority());
            data.put("retryCount", taskQueue.getRetryCount());
            data.put("errorMessage", taskQueue.getErrorMessage());
            data.put("createdAt", taskQueue.getCreatedAt());
            data.put("startedAt", taskQueue.getStartedAt());
            data.put("completedAt", taskQueue.getCompletedAt());

            return buildSuccessResponse("查询成功", data);

        } catch (Exception e) {
            log.error("查询任务队列状态失败: {}", taskId, e);
            return buildErrorResponse(CODE_NOT_FOUND, "任务不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 查询用户的任务队列
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserTaskQueue(@PathVariable Long userId) {
        log.info("查询用户任务队列: {}", userId);

        try {
            List<ZWikiTaskQueueEntity> taskQueues = taskQueueService.getUserTaskQueue(userId);

            List<Map<String, Object>> data = taskQueues.stream().map(task -> {
                Map<String, Object> item = new HashMap<>();
                item.put("taskId", task.getTaskId());
                item.put("taskType", task.getTaskType());
                item.put("status", task.getStatus());
                item.put("priority", task.getPriority());
                item.put("createdAt", task.getCreatedAt());
                item.put("startedAt", task.getStartedAt());
                item.put("completedAt", task.getCompletedAt());
                return item;
            }).collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("total", data.size());
            result.put("tasks", data);

            return buildSuccessResponse("查询成功", result);

        } catch (Exception e) {
            log.error("查询用户任务队列失败: {}", userId, e);
            return buildErrorResponse(CODE_ERROR, "查询失败: " + e.getMessage(), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取队列统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getQueueStats() {
        log.info("查询队列统计信息");

        try {
            Map<String, Object> stats = new HashMap<>();
            // 这里可以添加更多统计信息
            stats.put("message", "队列统计功能");

            return buildSuccessResponse("查询成功", stats);

        } catch (Exception e) {
            log.error("查询队列统计信息失败", e);
            return buildErrorResponse(CODE_ERROR, "查询失败: " + e.getMessage(), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // ========== 辅助方法 ==========

    private ResponseEntity<Map<String, Object>> buildSuccessResponse(String message, Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", CODE_SUCCESS);
        result.put("message", message);
        result.put("data", data);
        return ResponseEntity.ok(result);
    }

    private ResponseEntity<Map<String, Object>> buildErrorResponse(String code, String message, HttpStatus status) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("message", message);
        return ResponseEntity.status(status).body(result);
    }
}

